package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.basics.server.TollStationUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.basics.server.TollStationUploadResponse;
import io.renren.common.utils.CompletionStr;
import io.renren.common.utils.GUID;
import io.renren.modules.basedata.dao.OperlogDao;
import io.renren.modules.basedata.dao.TollStationUploadDao;
import io.renren.modules.basedata.entity.tbl_Operlog;
import io.renren.modules.basedata.entity.tbl_tollStation;
import io.renren.modules.basedata.service.TollStationUploadService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author Liuxx
 * @version 上传收费站信息
 */
@Service
public class TollStationUploadServiceImpl implements TollStationUploadService {

	private static final Logger log = Logger.getLogger(TollStationUploadServiceImpl.class);

	@Autowired
	OperlogDao operlogDao;
	@Autowired
	TollStationUploadDao tollStationUploadDao;
	@Override
	public String tollStationUpload() throws Exception {
		log.info("开始获取收费站信息！");
		int operResult = 0;
		List<tbl_tollStation> list = null;
		tbl_tollStation tollStation = null;
		tbl_Operlog operlog = new tbl_Operlog();
		list = getTollStationList();//获取收费站信息
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				tollStation = list.get(i);
				//收费站信息上传及变更接口
				TollStationUploadRequest request = new TollStationUploadRequest();
				request.setId(tollStation.getId());
				request.setName(tollStation.getName());
				request.setType(tollStation.getType());
				request.setTollPlazaCount(tollStation.getTollPlazaCount());
				request.setNeighborId(tollStation.getNeighborId());
				request.setOperation(tollStation.getFlag());
				//增加stationHex收费站HEX字符串
				String stationHex = getStationHex(tollStation.getOldid());
				tollStation.setStationHex(stationHex);
				request.setStationHex(stationHex);
				//获取发送文件名
				String fileName = ETCCommHelper.getFileName(request,"65");
				try{
					//指定响应的协议模型，调用upload发送数据
					TollStationUploadResponse response = ETCCommHelper.sdtsUpload(fileName, request,TollStationUploadResponse.class );
					log.info("上传收费站信息成功，服务器返回："+response.toJson());
					if(response!=null&&response.getInfo().equals("成功！")){
						//更新上传标志

						if(tollStationUploadDao.updateTollStation(tollStation)==1){
							log.info("更新收费站信息表上传标志成功!");
							operResult = 1;
							operlog = getOperlog(26,1,tollStation.getId(),fileName,operResult, response.getInfo(),"上传成功，更新成功");
						}else{
							log.info("更新收费站信息表上传标志失败!");
							operlog = getOperlog(26,1,tollStation.getId(),fileName ,operResult,response.getInfo(),"上传成功，更新失败");
						}
						operlogDao.insertlog(operlog);
					}else{
						log.info("上传收费站信息失败!失败原因："+response.getInfo());
						tollStationUploadDao.updateTollStationError(tollStation.getId());
						//sqlMapClient.update("tollBaseInfo_ORACLE.updateTollStationError",tollStation.getId());
						
						//getOperlog（操作类型，传输类型，发送文件名，接收文件名，操作结果，部中心返回结果，说明）
						operlog = getOperlog(26,1 ,tollStation.getId(),fileName ,0,response.getInfo(), response.toJson());
						operlogDao.insertlog(operlog);
					}
				}catch(IOException e){
					log.error("上传收费站信息失败！错误信息："+e.getMessage());
					tollStationUploadDao.updateTollStationError(tollStation.getId());
					//sqlMapClient.update("tollBaseInfo_ORACLE.updateTollStationError",tollStation.getId());
					
					operlog = getOperlog(26, 1, tollStation.getId(), fileName, 0,"IO异常", "出现IO异常，数据上传失败："+e.getMessage());
					operlogDao.insertlog(operlog);
					e.printStackTrace();
					continue;
				}catch (ApiRequestException apie) {
					log.error("上传收费站信息失败！错误信息："+apie.getMessage());
					tollStationUploadDao.updateTollStationError(tollStation.getId());

					operlog = getOperlog(26, 1, tollStation.getId(), fileName, 0,String.valueOf(apie.getErrCode()), "出现ApiRequestException异常，数据上传失败："+apie.getMessage());
					operlogDao.insertlog(operlog);
					apie.printStackTrace();
					continue;
				}
			}
				return "上传收费站信息结束！";
		}else{
			return "无收费站信息，上传结束...";
		}
	}
	
	//获取收费站信息
	@SuppressWarnings("unchecked")
	public List<tbl_tollStation> getTollStationList() throws IOException{
		List<tbl_tollStation> list;
		try{
			list = tollStationUploadDao.getTollStationList();
			//list = sqlMapClient.queryForList("tollBaseInfo_ORACLE.getTollStationList");
		}catch(Exception e){
			e.printStackTrace();
			log.error("获取收费站信息失败！错误信息：",e);
			throw new IOException("获取收费站信息失败:"+e.getMessage());
		}
		return list;
	}
	
	//获取operlog信息
	public tbl_Operlog getOperlog(int operType,int softType,String sendFileName,String reFileName,int operResult,String reResult, String content){
		tbl_Operlog operlog = new tbl_Operlog();
		operlog.setWastesn(new GUID().toString());
		operlog.setOperTime(new Date());
		operlog.setOpertype(operType);
		operlog.setSoftType(softType);
		operlog.setSendFileName(sendFileName);
		operlog.setReFileName(reFileName);
		operlog.setOperResult(operResult);
		operlog.setReResult(reResult);
		operlog.setContent(content);
		return operlog;
	}

	/**
	 * 获取收费站HEX码 6501010
	 * STATIONHEX = 6501(10转16)+01010(10转16) 
	 * @param ID 收费站编码
	 * @return
	 */  
	public String getStationHex(String ID){
	    String provinceId = Integer.toHexString(6501);
	    String stationId = CompletionStr.compStr0(Integer.toHexString(Integer.valueOf(ID.substring(2))),4) ;
		return (provinceId+stationId);
	}
}
